#include "whaleabstractconnect.h"
#include "cookiejar.h"

#include <qjson/parser.h>
#include <QTimer>
#include <QtDebug>
#include <QNetworkReply>

WhaleAbstractConnect::WhaleAbstractConnect( QObject * parent ) : QObject( parent ) {
    this->mConnector = new QNetworkAccessManager();

    // get active user cookies
    QList< QNetworkCookie > cookies = CookieJar::loginCookies();

    // give cookies to connector to allow API calls
    this->mConnector->cookieJar()->setCookiesFromUrl( cookies, QUrl( "http://socialwhale.com" ) );
}

void WhaleAbstractConnect::watch( QUrl url, QObject * receiver, const char * method ) {
    // set request to url
    QNetworkReply * reply = this->mConnector->get( QNetworkRequest( url ) );

    // call callback() when request is done
    this->connect( reply, SIGNAL( finished() ), this, SLOT( callback() ) );

    // keep receiver and method in memory to call receiver::method when done
    this->mCallbacks.insert( reply, QPair< QObject *, const char * >( receiver, method ) );
}

void WhaleAbstractConnect::callback() {
    QJson::Parser parser;
    bool ok;

    // get request reply
    QNetworkReply * reply = qobject_cast< QNetworkReply * >( this->sender() );

    // get associated receiver and method
    QObject * receiver = this->mCallbacks[ reply ].first;
    const char * method = this->mCallbacks[ reply ].second;

    // parse json
    QByteArray json = reply->readAll();
    QVariant results = parser.parse( json, &ok );

    // call receiver::method using QObject::connect and singal emit
    connect( this, SIGNAL( informCallback( QVariant ) ), receiver, method );
    emit this->informCallback( results );

    // disconnect receiver for safety
    disconnect( this, SIGNAL( informCallback( QVariant ) ), receiver, method );
}

QNetworkAccessManager * WhaleAbstractConnect::manager() {
    return this->mConnector;
}

void WhaleAbstractConnect::setCurrentStreamName( QString name ) {
    this->mCurrentStreamName = name;
}

QString WhaleAbstractConnect::currentStreamName() {
    return this->mCurrentStreamName;
}
